﻿using System.Linq;
using Rodunu.Business.Interfaces;
using Rodunu.Business.Models.User;
using Rodunu.Business.Logic;

namespace Rodunu.Clients.WPF.Controllers
{
    public class LoginController
    {
        private readonly IManageSettings _manageSettings;
        private ILogin _login;
        private IManageUser _manageUser;
        private User _loggedOnUser;

        public User LoggedOnuser
        {
            get
            {
                return _loggedOnUser;
            }
        }

        public LoginController(IManageSettings manageSettings)
        {
            _manageSettings = manageSettings;

            if (_manageSettings.CurrentSettings.AutoLogin)
            {
                SetCurrentUser();
            }
        }

        private void SetCurrentUser()
        {
            _loggedOnUser = (from user in _manageSettings.CurrentSettings.Users
                             where user.UserName == _manageSettings.CurrentSettings.LastUserLoggedIn
                             select user).SingleOrDefault();

            _manageSettings.CurrentSettings.LastUserLoggedIn = _loggedOnUser.UserName;
            _manageSettings.CurrentUser = _loggedOnUser;
            _manageSettings.SaveCurrentSettings();
        }

        public bool Login(string userName, string password, bool rememberUser, bool rememberPassword, bool autoLogIn)
        {
            if (_login == null)
                _login = new Login(_manageSettings);

            User user = _login.LoginUserOn(userName, password, rememberUser, rememberPassword, autoLogIn);
            if (user != null && !string.IsNullOrEmpty(user.UserName))
            {
                _loggedOnUser = user;
                _manageSettings.CurrentSettings.LastUserLoggedIn = _loggedOnUser.UserName;
                return true;
            }
            else
            {
                return false;
            }
        }

        public void SaveSettings()
        {
            _manageSettings.SaveCurrentSettings();
        }

        public bool CreateUser(User user, bool rememberUser, bool rememberPassword, bool autoLogIn)
        {
            if (_manageUser == null)
                _manageUser = new ManageUser(_manageSettings);

            _manageUser.CreateUser(user, rememberUser, rememberPassword, autoLogIn);

            SetCurrentUser();

            return true;
        }
    }
}
